#include <stdlib.h>
#include "datawindow.h"

PL_window * create_window(unsigned int len, unsigned int slide)
{
	PL_window * dw = (PL_window *)malloc(sizeof(PL_window));
    dw->length = len;
    dw->slide = slide;
    /* TODO: change to creating a PL_window of any type instead of just int */
	dw->data = calloc(len, (sizeof(int) * len));
    dw->p_prev_head = dw->data + (sizeof(int) * (len - slide));
    dw->p_head = dw->data;
    return dw;
}

void delete_window(PL_window * dw)
{
    free(dw->data);
    free((void *)dw);
}

void slide_window(PL_window * dw)
{
    /*
    unsigned int head_index = (unsigned int)(dw->p_head - dw->data);
    unsigned int slide_offset = (sizeof(int) * dw->slide);
    unsigned int end_index = (sizeof(int) * dw->length);
    */

    dw->p_prev_head = dw->p_head;
    /*dw->p_head = (dw->data + ((head_index + slide_offset) % end_index));*/
    dw->p_head = index_from_addr(dw, dw->p_head, dw->slide);
}

/*
fragmented_array get_frag_array(PL_window * dw)
{
    fragmented_array fragarr;
    fragarr.first_piece = dw->p_pre;
    return fragarr;
}
*/

void * index_from_addr(PL_window * dw, void * addr, unsigned int index)
{
    /* assert(dw != NULL); */
    /* assert(addr >= dw->data && addr < (dw->data + (sizeof(int) * dw->length))); */
    /* assert(index < dw->length); */
    unsigned int addr_index = (unsigned int)(addr - dw->data);
    unsigned int index_offset = (sizeof(int) * index);
    unsigned int end_index = (sizeof(int) * dw->length);

    return (dw->data + ((addr_index + index_offset) % end_index));
}
